#include "seqlist.h"

SeqList::SeqList()
{

}

void SeqList::create(int m_capacity)
{
    if(m_capacity >= 0){
/*
 * 思考为什么malloc的参数要这样么设置？
 * 头部保存这个顺序表（记录当前位置和容量大小）的信息，其余插入删除的都是节点
 */
        seq = (SeqListType *)malloc(sizeof(SeqListType) + sizeof(SeqListNode) * m_capacity);
    }
    if(seq == NULL){
        cout<<"Fail to create SeqList!"<<endl;
        exit(0);
    }
    seq->capacity = m_capacity;
    seq->length = 0;
/*
 * 使指针指向第一个节点
*/
    seq->node = (SeqListNode*)(seq + 1);
}

void SeqList::destory()
{
    free (seq);
}

void SeqList::clear()
{
    if(seq != NULL){
        seq->length = 0;
    }
}

bool SeqList::isEmpty()
{
    if(seq->length == 0)
        return true;
    else
        return false;
}

void SeqList::print()
{
    cout<<"SeqListData:"<<endl;
    for(int i = 0; i < seq->length; i++){
        cout<<(seq->node[i])<<endl;
    }
}

SeqListNode SeqList::getNode(int pos) const
{
    return seq->node[pos - 1];
}

void SeqList::insert(SeqListNode node, int pos)
{
    int i;
    /*判断插入的位置是否在合法,且只能依次插入*/
    if(pos < 1 || pos > seq->capacity){
        cout<<"fail to insert!"<<endl;
        return ;
    }
    /*判断线性表表是否已经插满,如果插满了就要申请空间*/
    //code

    if(pos < seq->length){
        seq->node[pos] = node;
    }
    if(pos > seq->length){
        for(i = seq->length; i > pos; i--){
            seq->node[i] = seq->node[i-1];
        }
        seq->node[i] = node;
        seq->length++;
    }
}

int SeqList::locate(SeqListNode node)
{
    for(int i = 1; i <= seq->length; i++){
        if((seq->node[i - 1]) == node){
            return i;
        }
    }
}

int SeqList::getLength() const
{
    return seq->length;
}

int SeqList::getCapacity() const
{
    return seq->capacity;
}
